﻿using AutoMapper;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules.MaterialOutAsk;
using MES.Server.API.Dto.Warehouse;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Production_Modules.MaterilaOutAsk
{
    public class GetMaterialOutAskHander : IRequestHandler<GetMaterialOutAskCommand, ApiPaging<GetMaterialOutAskOutPut>>
    {
        private readonly IRepository<MaterialOutAskModel> materialOutAskRepo;
        private readonly IMapper mapper;
        public GetMaterialOutAskHander(IRepository<MaterialOutAskModel> materialOutAskRepo, IMapper mapper)
        {
            this.materialOutAskRepo = materialOutAskRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 物料入库申请单列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<GetMaterialOutAskOutPut>> Handle(GetMaterialOutAskCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<GetMaterialOutAskOutPut>();
            var materialOutAsk = materialOutAskRepo.GetAll().Where(x=>x.IsDel==false);
            var zhi = mapper.Map<List<GetMaterialOutAskOutPut>>(materialOutAsk);
            if(!string.IsNullOrEmpty(request.PurchaseOrderCode))
            {
                zhi = zhi.Where(x => x.PurchaseOrderCode.Contains(request.PurchaseOrderCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductMaterialsName))
            {
                zhi = zhi.Where(x => x.ProductMaterialsName.Contains(request.ProductMaterialsName)).ToList();
            }
            result.Totalcount = zhi.Count();
            result.TotalPage = zhi.OrderByDescending(x=>x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Code = StatusCode.Success;   
            return Task.FromResult(result);
        }
    }
}
